import { reqLogin, reqLogout, reqUserInfo } from '@/api/authority/user/index.ts'
import type {
    LoginResponse,
    LoginUser,
    UserInfoResponse,
} from '@/api/authority/user/type'
import type { UserState } from './types/type'
import { defineStore } from 'pinia'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '@/utils/token'
// 引入常量路由
import { constantRoutes, anyRoute, asyncRoutes } from '@/router/routes.ts'
import { ResponseData } from '@/api/type'
import router from '@/router'
//引入深拷贝方法
//@ts-expect-error
import cloneDeep from 'lodash/cloneDeep';
import { RouteRecordRaw } from 'vue-router'
//用于过滤当前用户需要展示的异步路由
function filterAsyncRouter(asyncRoutes: RouteRecordRaw[], routes: string[]) {
    return asyncRoutes.filter((item) => {
        if (routes.includes(item.path)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRouter(item.children, routes)
            }
            return true
        } else {
            return false
        }
    })
}
const useUserStore = defineStore('User', {
    state(): UserState {
        return {
            token: GET_TOKEN(), //用户的token
            routes: constantRoutes,
            nickName: '',
            avatar: '',
            buttons: [],
            roles: [],
        }
    },
    actions: {
        // 用户登录的方法
        async userLogin(loginUser: LoginUser) {
            const result: LoginResponse = await reqLogin(loginUser)
            if (result.code === 2000) {
                this.token = result.data.token
                SET_TOKEN(result.data.token)
                return Promise.resolve('ok')
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //获取用户信息
        async userInfo() {
            const result: UserInfoResponse = await reqUserInfo()
            if (result.code === 2000) {
                const {
                    data: { nickName, avatar, roles, buttons, routes },
                } = result
                this.$patch((state) => {
                    state.avatar = avatar
                    state.buttons = buttons
                    state.nickName = nickName
                    state.roles = roles
                })
                // 计算当前用户的异步路由
                const userAsyncRoute = filterAsyncRouter(cloneDeep(asyncRoutes), routes)
                // 先把store的routes保存
                this.routes = [...constantRoutes, ...userAsyncRoute, anyRoute];
                // 再往router里面追加route
                [...userAsyncRoute].forEach((route: RouteRecordRaw) => {
                    router.addRoute(route)
                })
                router.addRoute(anyRoute)
                return Promise.resolve('ok')
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async logout() {
            const result: ResponseData<null> = await reqLogout()
            if (result.code === 2000) {
                this.resetToken()
                return Promise.resolve()
            } else {
                this.resetToken()
                return Promise.reject(new Error(result.message))
            }
        },
        resetToken() {
            // 先清除token
            REMOVE_TOKEN()
            // 再去重置
            this.$reset()
        },
    },
    getters: {},
})
export default useUserStore
